package com.wpx.fileSys.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONObject;

import com.wpx.fileSys.dao.FileDao;
import com.wpx.fileSys.dao.UserDao;
import com.wpx.fileSys.dao.impl.FileDaoImpl;
import com.wpx.fileSys.dao.impl.UserDaoImpl;
import com.wpx.fileSys.utils.Token;

/**
 * Servlet implementation class updateServlet
 */
@WebServlet("/updateServlet")
public class updateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public updateServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json; charset=utf-8");	

		request.setCharacterEncoding("UTF-8");
		
		PrintWriter out = null;	
		out = response.getWriter();
		String username=(String) request.getSession().getAttribute("username");
		String token = (String) request.getSession().getAttribute("token");
		Token tokenTool=new Token();
		JSONObject result=new JSONObject();
		result.put("msg", "0");
		if (!tokenTool.verifyToken(username, token)) {
			result.put("msg", "token过期");
			out.write(result.toString());
			return;
		}
		FileDao dao=new FileDaoImpl();
		String msg=result.getString("msg");
		
		if (dao.deleteFiles(username)) {
			if (!dao.updateFiles(username)) {
				msg="更新过程中出现错误";
			}
		}else {
			msg="删除过程中出现错误";
		}
		result.put("msg", msg);

		out.write(result.toString());
		
//		RequestDispatcher dispatcher = request.getRequestDispatcher("/index.html");
//		dispatcher .forward(request, response);
		out.flush();
		out.close();
		
		
		
	}

}
